package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.*;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;

@Service
public class WorkspaceServiceImpl implements WorkspaceService {
    @Autowired
    private WorkspaceMapper workspaceMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public BusinessDataVO businessData(LocalDate date) {
        Integer newUsers = userMapper.countUserByDate(date);
        Integer orderCount = orderMapper.findStatusAndDate(null, date);
        Integer validOrderCount = orderMapper.findStatusAndDate(Orders.COMPLETED, date);
        double orderCompletionRate=0.0;
        if(orderCount!=0){
           orderCompletionRate = BigDecimal.valueOf(validOrderCount).divide(BigDecimal.valueOf(orderCount),2, RoundingMode.HALF_UP).doubleValue();
        }
        Double turnover = orderMapper.findStatusAndTime(Orders.COMPLETED, date);

        double unitPrice=0.0;
        if(validOrderCount!=0){
            unitPrice = BigDecimal.valueOf(turnover).divide(BigDecimal.valueOf(validOrderCount),2, RoundingMode.HALF_UP).doubleValue();
        }
        return BusinessDataVO.builder()
                .newUsers(newUsers)
                .orderCompletionRate(orderCompletionRate)
                .turnover(turnover)
                .unitPrice(unitPrice)
                .validOrderCount(validOrderCount)
                .total(orderCount)
                .build();
    }

    @Override
    public OrderOverViewVO overviewOrders(LocalDate date) {
        OrderOverViewVO vo = orderMapper.overviewOrders(date);

        return vo;
    }

    @Override
    public DishOverViewVO overviewDishes() {
       Integer count1 = dishMapper.countStatus(StatusConstant.DISABLE);
       Integer count2 = dishMapper.countStatus(StatusConstant.ENABLE);
        return DishOverViewVO.builder()
                .discontinued(count1)
                .sold(count2)
                .build();
    }

    @Override
    public SetmealOverViewVO overviewSetmeals() {
        Integer count1 = setmealMapper.countStatus(StatusConstant.DISABLE);
        Integer count2 = setmealMapper.countStatus(StatusConstant.ENABLE);
        return SetmealOverViewVO.builder()
                .discontinued(count1)
                .sold(count2)
                .build();
    }
}
